<template>
  <div class="content-left-wrap">
    <Card class="left-wrap">
      <div slot="title" class="filter-wrapper">
        <Form slot="search-bar" inline ref="formCustom">
          <FormItem>
            <RadioGroup v-model="chartType" @on-change="handleChangeType">
              <Radio class="radio-text" label="fb">分布图</Radio>
              <Radio class="radio-text" label="rl">热力图</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem>
            <Dropdown placement="bottom-start" trigger="custom" :visible="paramsVisibile">
              <Button type="info" @click="handleParams(true)" size="small">参数设置<Icon type="ios-arrow-down" /></Button>
              <DropdownMenu slot="list" class="fb">
                <DropdownItem v-if="showFB" style="margin-top: 30px;margin-bottom: 15px;">
                  <div class="name" style="line-height: 1;">寿命等级</div>
                  <div class="super-slider">
                    <super-slider :max="15" :width="360" @changeSuperSlider="changeSuperSlider" :data="defaultLevel" />
                  </div>
                  <span class="show-num">&nbsp;</span>
                </DropdownItem>
                <DropdownItem v-if="showFB">
                  <div class="name">点半径</div>
                  <div class="slider">
                    <Slider :min="1" :max="10" v-model="pointMultiple"></Slider>
                  </div>
                  <span class="show-num">x {{ pointMultiple }}</span>
                </DropdownItem>
                <DropdownItem v-if="showRL">
                  <div class="name">数据范围</div>
                  <div class="slider">
                    <Slider :min="1" :max="100" v-model="filterData.xCut"></Slider>
                  </div>
                  <span class="show-num">{{ filterData.xCut }} x {{ filterData.xCut }}</span>
                </DropdownItem>
                <DropdownItem v-if="showRL">
                  <div class="name">寿命等级</div>
                  <div class="slider">
                    <Slider :max="15" range v-model="filterData.hotLevel"></Slider>
                  </div>
                  <span class="show-num">{{ filterData.hotLevel[0] }} - {{ filterData.hotLevel[1] }}</span>
                </DropdownItem>
                <div style="text-align: right;margin-right:16px;">
                  <Button type="primary" @click="handleParams(false)" size="small">关闭</Button>
                </div>
              </DropdownMenu>
            </Dropdown>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSaveParams" :loading="saveBtnLoading" size="small">保存参数</Button>
          </FormItem>
          <FormItem v-if="showFB">
            <Dropdown trigger="custom" :visible="fxToolVisibile">
              <Button type="info" size="small" @click="fxToolHandle(true)">表具异常分析<Icon type="ios-arrow-down" /></Button>
              <DropdownMenu slot="list" class="fb">
                <DropdownItem>
                  <div class="name" style="width: 100px;">异常数据比例</div>
                  <div class="slider">
                    <Slider :min="0" :max="100" v-model="ycsjPer" />
                  </div>
                  <span class="show-num">{{ ycsjPer }} %</span>
                </DropdownItem>
                <DropdownItem>
                  <div class="name" style="width: 100px;">缺失数据比例</div>
                  <div class="slider">
                    <Slider :min="0" :max="100" v-model="qsPer" />
                  </div>
                  <span class="show-num">{{ qsPer }} %</span>
                </DropdownItem>
                <div style="text-align: right;margin-right:16px;">
                  <Button type="primary" @click="fxToolHandle(false)" size="small">关闭</Button>
                </div>
              </DropdownMenu>
            </Dropdown>
          </FormItem>
        </Form>
        <div class="collapse-icon" @click="collapseRight">
          <span v-if="collapseIcon" title="缩小">
            <Icon type="icon iconfont icon-xiangqian" />
          </span>
          <span v-else title="放大">
            <Icon type="icon iconfont icon-xianghou" />
          </span>
        </div>
      </div>
      <div class="chart-container">
        <div class="chart" v-if="showFB" key="effect-scatter-map">
          <effect-scatter-map
            id="dis-effect-scatter-map"
            :fetchData="loadFBChartData"
            :mapData="effectScatterChartList"
            :collapseIcon="collapseIcon"
            :topNum="topNum"
            :level="level"
            :pointMultiple="pointMultipleChange"
            @pointClick="pointClickHandle"
          />
        </div>
        <div class="chart" v-if="showRL" key="heat-map">
          <heat-map
            id="headtMap"
            :fetchData="loadRLChartData"
            @checkArea="checkArea"
            @areaClick="areaClickHandle"
            :params="params"
            :chartData="headtMapData"
            :shrink="collapseIcon"
          />
        </div>
      </div>
    </Card>
  </div>
</template>
<script>
import { each, isNull } from 'lodash'
import { createNamespacedHelpers } from 'vuex'
import SuperSlider from '@/commons/super-slider'
const { mapState, mapActions } = createNamespacedHelpers('meterManageDestribution')

export default {
  name: 'distribution-content-left',
  components: {
    SuperSlider,
    EffectScatterMap: () => import('@/commons/charts/EffectScatterMap'),
    HeatMap: () => import('@/commons/charts/HeatMap')
  },
  data() {
    return {
      chartType: 'fb',
      saveBtnLoading: false,
      topNum: 0,
      level: [],
      params: {},
      pointMultiple: 1,
      pointMultipleChange: 1,
      paramsVisibile: false,
      fxToolVisibile: false,
      filterData: {
        level: undefined,
        xMinSize: undefined,
        xMaxSize: undefined,
        yMinSize: undefined,
        yMaxSize: undefined,
        hotLevel: [0, 0],
        yCut: undefined,
        xCut: undefined
      },
      defaultLevel: null,
      effectScatterChartList: [],
      headtMapData: [],
      ycsjPer: 0,
      qsPer: 0
    }
  },
  computed: {
    ...mapState(['fbChartList', 'rlChartList', 'collapseIcon', 'qsScore', 'ycsjScore']),
    showRL() {
      return this.chartType === 'rl'
    },
    showFB() {
      return this.chartType === 'fb'
    }
  },
  watch: {
    fbChartList() {
      this.effectScatterChartList = this.modifyEffectScatterData(this.fbChartList)
    },
    rlChartList: {
      handler() {
        this.headtMapData = this.modifyHeatMapData(this.rlChartList)
      },
      deep: true
    }
  },
  beforeDestroy() {
    document.removeEventListener('mouseup', this.handleMouseUp)
    this.clearStore()
  },
  mounted() {
    this.sliderListerMouseUp()
    this.getUserParams()
  },
  methods: {
    ...mapActions([
      'loadFBChartData',
      'loadUserParams',
      'loadRLChartData',
      'changeChartType',
      'changeCollapseIcon',
      'changeCurrentMeterId',
      'loadMeterDetail',
      'loadHPieCharList',
      'loadSaveParams',
      'changeHPieChartData',
      'changeMeterDetail',
      'changeCurrentMeterId',
      'loadDiagReport',
      'clearStore',
      'loadHBarCharData',
      'changeQsScore',
      'changeYcsjScore'
    ]),
    /**
     * @msg: 滑动条绑定鼠标松开事件
     * @param {type}
     * @return:
     */
    sliderListerMouseUp() {
      document.addEventListener('mouseup', this.handleMouseUp)
    },
    async getUserParams() {
      const { code, date } = await this.loadUserParams()
      if (code === 200) {
        const { level, xCut, yCut, hotLevel, ...rest } = date
        // eslint-disable-next-line no-eval
        const { min, max } = eval('(' + hotLevel + ')')
        this.params = date
        let l = []
        try {
          l = JSON.parse(level)
        } catch (error) {
          l = []
        }
        this.level = l
        this.defaultLevel = l
        this.topNum = l[l.length - 1] ? l[l.length - 1].min : 15
        this.pointMultiple = l[0].pointMultiple || 1
        this.pointMultipleChange = l[0].pointMultiple || 1

        this.filterData = {
          ...this.filterData,
          ...rest,
          xCut,
          yCut,
          hotLevel: [min, max],
          level: l
        }
      }
    },
    /**
     * 整理散点图数据
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    modifyEffectScatterData(data = []) {
      const mapData = []
      each(data, item => {
        const { meterId, years, latitude, longitude, missRate = 0, abnormalRate = 0 } = item
        const _missRate = isNull(missRate) ? 0 : missRate
        const _abnormalRate = isNull(abnormalRate) ? 0 : abnormalRate
        if (_missRate >= this.qsPer && _abnormalRate >= this.ycsjPer) {
          const year = this.changeLevel(years) || 0
          mapData.push({
            name: meterId,
            value: [longitude, latitude, year]
          })
        }
      })

      return mapData
    },
    /**
     * 年份等级处理
     * @param  {[type]} year [description]
     * @return {[type]}      [description]
     */
    changeLevel(year = 0) {
      const { level: l } = this.filterData
      for (let i = 0; i < l.length; i++) {
        const { min, max } = l[i]
        if (Number(year) >= Number(min) && Number(year) < Number(max)) {
          return max
        }
      }
    },
    /**
     * 整理热力图数据
     * @return {[type]} [description]
     */
    modifyHeatMapData(data = []) {
      const _data = []
      each(data, (item, index) => {
        const { x, y, count } = item
        _data.push([x, y, count])
      })
      return _data
    },
    handleChangeType(type) {
      this.changeHPieChartData([])
      this.changeMeterDetail({})
      this.changeCurrentMeterId(undefined)
      this.changeChartType(type)
    },
    async handleSaveParams() {
      this.paramsFlag = false
      this.saveBtnLoading = true
      const { hotLevel, xCut, level } = this.filterData
      const newLevel = []
      each(level, item => {
        newLevel.push({
          ...item,
          pointMultiple: this.pointMultiple
        })
      })
      const data = {
        ...this.filterData,
        yCut: xCut,
        hotLevel: JSON.stringify({ min: hotLevel[0], max: hotLevel[1] }),
        level: JSON.stringify(newLevel)
      }
      const { code, msg } = await this.loadSaveParams(data)
      this.saveBtnLoading = false
      this.handleParams(false)
      if (code === 200) {
        this.$Message.success(msg)
        this.loadDiagReport()
        await this.getUserParams()
        if (this.chartType === 'rl') {
          this.loadRLChartData()
        } else if (this.chartType === 'fb') {
          this.loadFBChartData()
        }
      } else {
        this.$Message.error('数据保存失败')
      }
    },
    collapseRight() {
      this.changeCollapseIcon(!this.collapseIcon)
    },
    pointClickHandle(data) {
      const { name } = data
      if (name) {
        this.changeCurrentMeterId(name)
        this.loadMeterDetail()
      }
    },
    areaClickHandle(data) {
      const { value = [] } = data
      const [x, y] = value
      if (value) {
        this.loadHPieCharList({
          x,
          y
        })
      }
    },
    handleParams(flag) {
      this.fxToolVisibile = false
      this.paramsVisibile = flag
    },
    changeSuperSlider(levelArr) {
      this.filterData = {
        ...this.filterData,
        level: levelArr
      }
      this.level = levelArr
      this.topNum = levelArr[levelArr.length - 1] ? levelArr[levelArr.length - 1].min : 15
      this.$nextTick(() => {
        const newData = this.modifyEffectScatterData(this.fbChartList)
        this.effectScatterChartList = newData
      })
    },
    checkArea(data) {
      const { xMinSize, xMaxSize, yMinSize, yMaxSize } = data
      this.filterData = {
        ...this.filterData,
        xMinSize,
        xMaxSize,
        yMinSize,
        yMaxSize
      }
    },
    handleMouseUp() {
      if (Number(this.pointMultiple) !== Number(this.pointMultipleChange)) {
        this.pointMultipleChange = this.pointMultiple
      }
      if ((this.qsScore !== this.qsPer) || (this.ycsjScore !== this.ycsjPer)) {
        this.changeQsScore(this.qsPer)
        this.changeYcsjScore(this.ycsjPer)
        this.filterFxList()
        this.loadHBarCharData({
          missRate: this.qsPer,
          abnormalRate: this.ycsjPer
        })
      }
    },
    fxToolHandle(flag) {
      this.paramsVisibile = false
      this.fxToolVisibile = flag
    },
    /**
     * desc: 根据分析进行数据筛选
     * param {type}
     * return {type} void
     */
    filterFxList() {
      this.effectScatterChartList = this.modifyEffectScatterData(this.fbChartList)
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';

.content-left-wrap {
  width: 100%;
  height: 100%;

  .super-slider,
  .slider {
    flex: 1;
  }

  .filter-wrapper {
    position: relative;

    @{deep} .ivu-select-dropdown {
      width: 500px;
    }

    @{deep} .ivu-dropdown-item {
      display: flex;

      .name {
        line-height: 34px;
        margin-right: 15px;
        margin-left: 0;
        width: 60px;
      }

      .show-num {
        line-height: 34px;
        margin-left: 10px;
        width: 70px;
      }
    }
    .ivu-form-item-content {
      line-height: 30px;
    }
    .ivu-form-item {
      margin-top: 0;
      margin-bottom: 0;
    }

    .radio-text {
      margin-right: 10px;
      vertical-align: middle;
    }
  }

  .chart-container {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .chart {
    width: 100%;
    height: 100%;
  }

  .collapse-icon {
    position: absolute;
    right: 0;
    top: 6px;
    width: 22px;
    height: 22px;
    text-align: center;
    line-height: 20px;
    cursor: pointer;
    font-size: 12px;
  }
}
</style>
